package it.gameplanet.server;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.jdo.annotations.PrimaryKey;
import javax.persistence.Id;

public class PersistenceHelper {
	public static <T> Object findPrimaryKey(T tInstance) {
		if (tInstance == null) {
			return null;
		}
		for (Field l : tInstance.getClass().getDeclaredFields()) {
			if (l.getAnnotation(PrimaryKey.class) != null
					|| l.getAnnotation(Id.class) != null) {
				l.setAccessible(true);
				try {
					return l.get(tInstance);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
					return null;
				} catch (IllegalAccessException e) {
					e.printStackTrace();
					return null;
				}
			}
		}
		return new IllegalArgumentException("Class "
				+ tInstance.getClass().getName()
				+ " does not have a method called getId()");
	}

	public static <T> void copyPersistentFields(Object entity, T tInstance)
			throws IllegalAccessException, NoSuchMethodException,
			InvocationTargetException {
		for (Method f : tInstance.getClass().getMethods()) {
			if (f.getName().startsWith("set")
					&& Character.isUpperCase(f.getName().charAt(3))) {
				f.setAccessible(true);
				Method getter = tInstance.getClass().getMethod(
						"get" + f.getName().substring(3));
				getter.setAccessible(true);
				f.invoke(entity, getter.invoke(tInstance));
			}
		}
	}
	
	
}
